﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;

namespace WebUI
{
    public partial class BasePage : System.Web.UI.Page
    {
        public const string ID = "id";
        public const string CUSTID = "custid";
        public const string KEY = "key";
        public const string MODE = "mode";
        public const string EDIT_MODE = "edit";
        public const string ADD_MODE = "new";
        public const string VIEW_MODE = "view";
        public const string DIALOG_RESULT = "dialog_result";
        public const string SESSION_USER = "session_user";
        public const string VALIDATE = "validate";
        public const string REPORT_SOURCE = "report_source";
        public const string JOB_ID = "jobID";

        public const string DEFAULT_PAGE = @"/Default.aspx";
        public const string PRODUCT_PAGE = @"/BusinessCardPaper.aspx;/EditPages/EditPaper.aspx;/Product.aspx;/ProductImage.aspx;/EditPages/EditProduct.aspx;/EditPages/EditCategory.aspx;/StockTake.aspx;/StockTransfer.aspx;/EditPages/EditLocation.aspx;VoucherManagement.aspx";
        public const string PURCHASE_PAGE = @"/PurchaseOrder.aspx;/EditPages/EditPurchaseDetails.aspx";
        public const string SALE_PAGE = @"/Sales.aspx;/SaleRefund.aspx;/EditPages/EditInvoiceDetails.aspx;/EditPages/InvoiceViewer.aspx;/EditPages/PaymentHistViewer.aspx";
        public const string SUPPLIER_PAGE = @"/Supplier.aspx;/EditPages/EditSupplier.aspx";
        public const string USERS_PAGE = @"/Users.aspx;/EditPages/EditUser.aspx";
        public const string ROLES_PAGE = @"/Roles.aspx;/EditPages/EditRole.aspx";
        public const string BRANCH_PAGE = @"/Branches.aspx;/EditPages/EditBranch.aspx";
        public const string REPAIR_PAGE = "";//@"/Repair.aspx;/Refund.aspx;/EditPages/ViewRepair.aspx;/EditPages/ViewRepairBoxes.aspx;/EditPages/CallCustomer.aspx;/EditPages/RepairLookup.aspx;/EditPages/EditRepairModel.aspx;/EditPages/ProblemList.aspx;/EditPages/RepairBoxes.aspx;";
        public const string CUSTOMER_PAGE = @"/Customer.aspx;/CustomerOrders.aspx;/CustomerRequest.aspx";
        public const string EDIT_CUSTOMER_PAGE = @"/EditPages/EditCustomer.aspx";
        public const string EDIT_CUSTOMER_TYPE_PAGE = @"/EditPages/EditCustomerType.aspx";
        public const string CONTRACT_PAGE = "";//@"/Contract.aspx;/EditPages/AddService.aspx;/EditPages/ViewContracts.aspx";
        public const string REPORT_PAGE = @"/Report.aspx;/StockTakeReport.aspx;/Report.aspx;/CustomerStatement.aspx;/EODReport.aspx;/UserRecord.aspx;/SaleReport.aspx;/EditPages/Receivable.aspx;/EditPages/Payable.aspx";
        public const string EXPENSE_PAGE = @"/Expenses.aspx;/EditPages/EditExpense.aspx";

        public void ShowErrorMessage(Control parent, String msg)
        {
            String div = "<div class='{0}'>{1}</div>";
            Literal lit = new Literal();
            lit.Text = String.Format(div, "labelError", msg);

            parent.Controls.Add(lit);
        }

        public void ShowHintMessage(Control parent, String msg)
        {
            String div = "<div class='{0}'>{1}</div>";
            Literal lit = new Literal();
            lit.Text = String.Format(div, "labelHint", msg);

            parent.Controls.Add(lit);
        }

        public static SystemVariables SysVars
        {
            get { return SystemVariables.SysVars; }
        }

        public View_Users SessionUser
        {
            get 
            {
                return (View_Users)Session[SESSION_USER];    
            }
            set
            {
                Session[SESSION_USER] = value;
            }
        }

        public void CloseDlg(int res)
        {
            ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("window.returnValue='{0}';window.close();", res), true);
        }

        public void CloseDlg(string res)
        {
            ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("window.returnValue='{0}';window.close();", res), true);
        }

        protected bool ControlAccess()
        {
            string pageUrl =  HttpContext.Current.Request.Url.LocalPath;

            if (pageUrl.Contains("/EditPages/"))
            {
                if (!PRODUCT_PAGE.Contains(pageUrl)
                && !SALE_PAGE.Contains(pageUrl)
                && !SUPPLIER_PAGE.Contains(pageUrl)
                && !PURCHASE_PAGE.Contains(pageUrl)
                && !REPAIR_PAGE.Contains(pageUrl)
                && !REPORT_PAGE.Contains(pageUrl)
                && !CUSTOMER_PAGE.Contains(pageUrl)
                && !USERS_PAGE.Contains(pageUrl)
                && !ROLES_PAGE.Contains(pageUrl)
                && !BRANCH_PAGE.Contains(pageUrl)
                && !CONTRACT_PAGE.Contains(pageUrl)
                && !EXPENSE_PAGE.Contains(pageUrl))
                    return true;
            }

            pageUrl = System.IO.Path.GetFileName(pageUrl);

            if (DEFAULT_PAGE.Contains(pageUrl))
                return true;

            return
                (SessionUser.Products == true && PRODUCT_PAGE.Contains(pageUrl))
                || (SessionUser.Sales == true && SALE_PAGE.Contains(pageUrl))
                || (SessionUser.Suppliers == true && SUPPLIER_PAGE.Contains(pageUrl))
                || (SessionUser.Purchase == true && PURCHASE_PAGE.Contains(pageUrl))
                || (SessionUser.Repair == true && REPAIR_PAGE.Contains(pageUrl))
                || (SessionUser.Report == true && REPORT_PAGE.Contains(pageUrl))
                || (SessionUser.Customers == true && CUSTOMER_PAGE.Contains(pageUrl))
                || (SessionUser.Admin == true && USERS_PAGE.Contains(pageUrl))
                || (SessionUser.Admin == true && ROLES_PAGE.Contains(pageUrl))
                || (SessionUser.SystemAdmin == true && BRANCH_PAGE.Contains(pageUrl))
                || (SessionUser.Contracts == true && CONTRACT_PAGE.Contains(pageUrl))
                || (SessionUser.Expense == true && EXPENSE_PAGE.Contains(pageUrl))
                ;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            if (SessionUser == null)
            {
                if (Master is Application)
                    Response.Redirect("Login.aspx?url=" + this.Request.Url);
                else
                    Server.Transfer("SessionExpired.htm");

                Session.Abandon();
                Session.Clear();
                
                return;
            }

            if(!IsPostBack && !ControlAccess())
                Server.Transfer("AccessDenied.aspx");

            Page.MaintainScrollPositionOnPostBack = true;

            if (Master is Application)
            {
                ((Application)Master).SetSysDate(DateTime.UtcNow.AddHours(SysVars.TimeZone).ToString(SysVars.DateFormat));
                ((Application)Master).SetSysUser(Branches.CurrentBranch.s_Name + " - " + SessionUser.FullName + " - " + SessionUser.RoleName);
            }
        }
    }
}
